package com.testingedu.jdbcDao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.testingedu.common.QueryResult;
import com.testingedu.model.TMenu;
import com.testingedu.model.TMenuInRole;
import com.testingedu.model.TUser;

public class TMenuInRoleDao extends BaseDao<TMenuInRole> {

	public TMenuInRoleDao() {
		clazz = TMenuInRole.class;
	}

	public void list(QueryResult queryResult, TUser tUser) throws Exception{
		StringBuffer sql = new StringBuffer(
				"select * from t_menu tp where 1=1");
		List<Object> values = new ArrayList<Object>();
		if (tUser != null) {
			if (tUser.getName() != null && tUser.getName().trim().length() > 0) {
				sql.append(" and tp.name = ?");
				values.add(tUser.getName());
			}
		}
		try {
			this.myJdbcSetValuesAndExecuteQuery(sql.toString(), values);
			queryResult.setResultList(_resultSetToList(rs));
		} finally {
			close();
		}
		sql.replace(7, 8, "count(*)");
		try {
			this.myJdbcSetValuesAndExecuteQuery(sql.toString(), values);
			rs.next();
			queryResult.setAllCount(new Long(rs.getInt(1)));
		} catch (SQLException e) {
			e.printStackTrace();
			throw new Exception();
		} finally {
			close();
		}
	}
	
	public boolean hasAdd(Integer roleId, Integer menuId) throws Exception{
		String sql = "select tmir.menu_id from t_menu_in_role tmir where tmir.menu_id = ? and tmir.role_id = ?";
		List<Object> values = new ArrayList<Object>();
		values.add(menuId);
		values.add(roleId);
		try {
			this.myJdbcSetValuesAndExecuteQuery(sql, values);
			if (rs.next()) {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new Exception();
		} finally {
			this.close();
		}
		return false;
	}
	
	public void add(Integer roleId, List<Integer> menuIds) throws Exception{
		List<Object> values = new ArrayList<Object>();
		List<Integer> need = new ArrayList<Integer>();
		boolean go = true;
		TMenuDao tMenuDao = new TMenuDao();
		for (Integer integer : menuIds) {//将必须添加进来的父菜单找到
			need.add(integer);
			go = true;
			while (go) {//循环查找父菜单
				TMenu tMenu = tMenuDao.hasParents(integer);	//得到父菜单
				if (tMenu != null) {
					if (!this.hasAdd(roleId, tMenu.getId())) {	//查看父菜单是否已经被添加进来了
						if(!need.contains(tMenu.getId())) {
							need.add(tMenu.getId());
						}
						integer = tMenu.getId();	//继续查找
					} else {
						go = false;
					}
				} else {
					go = false;
				}
			}
		}
		StringBuffer sql = new StringBuffer("insert into t_menu_in_role(menu_id,role_id) values");
		try {
			for (int i = 0; i < need.size(); i++) {
				sql.append(" (?,?)");
				values.add(need.get(i));
				values.add(roleId);
				if(need.size() > 1 && i < (need.size() - 1)) {
					sql.append(",");
				}
			}
			this.myJdbcSetValuesAndExecuteSaveOrUpdateOrDelete(sql.toString(), values);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		}
		finally {
			this.close();
		}
	}

	public void delete(Integer roleId, List<Integer> menuIds) throws Exception{
		for (Integer integer : menuIds) {
			System.out.println("delete Menu Id:"+integer);
		}
		TMenuDao tMenuDao = new TMenuDao();
		boolean go = true;
		for (Integer integer : menuIds) {
			go = true;
			while(go) {		//依次删除被添加进来的父菜单
				TMenu tMenu = tMenuDao.hasParents(integer);//得到被添加进来的父级菜单
				this.delete(roleId, integer);	//删除此菜单
				if(tMenu != null) {	//父菜单不为空
					if(!this.hasBrotherAdd(roleId, tMenu.getId(), integer)) {//查看本次被删除的菜单是否含有兄弟
						integer = tMenu.getId();//下一次将被删除
					} else {
						go = false;
					}
				} else {
					go = false;
				}
			}
		}
	}
	
	public boolean hasBrotherAdd(Integer roleId, Integer superId,Integer menuId) throws Exception{
		String sql = "select tmir.menu_id from t_menu_in_role tmir where tmir.role_id = ? and tmir.menu_id in (select tm.id from t_menu tm where tm.super_id = ? and tm.id != ?)";
		List<Object> values = new ArrayList<Object>();
		values.add(roleId);
		values.add(superId);
		values.add(menuId);
		try {
			this.myJdbcSetValuesAndExecuteQuery(sql, values);
			if(rs.next()) {
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new Exception();
		}
		finally {
			this.close();
		}
		return false;
	}
	
	public void add(TUser tUser) throws Exception{
		String sql = "insert into t_menu(account,password,name,photo_path,description,certificate_id,certificate_name) values(?,?,?,?,?,?,?)";
		List<Object> values = new ArrayList<Object>();
		values.add(tUser.getAccount());
		values.add(tUser.getPassword());
		values.add(tUser.getName());
		values.add(tUser.getPhotoPath());
		values.add(tUser.getDescription());
		values.add(tUser.getCertificateId());
		values.add(tUser.getCertificateName());
		try {
			this.myJdbcSetValuesAndExecuteSaveOrUpdateOrDelete(sql, values);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		} finally {
			close();
		}
	}

	public void update(TUser tUser) throws Exception{
		String sql = "update t_menu set name = ?, description = ? where id=?";
		List<Object> values = new ArrayList<Object>();
		values.add(tUser.getName());
		values.add(tUser.getDescription());
		values.add(tUser.getId());
		try {
			this.myJdbcSetValuesAndExecuteSaveOrUpdateOrDelete(sql, values);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		} finally {
			close();
		}
	}

	public void delete(Integer roleId, Integer menuId) throws Exception{
		String sql = "delete from t_menu_in_role where role_id = ? and menu_id = ?";
		List<Object> values = new ArrayList<Object>();
		values.add(roleId);
		values.add(menuId);
		try {
			this.myJdbcSetValuesAndExecuteSaveOrUpdateOrDelete(sql, values);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception();
		} finally {
			close();
		}
	}

	public List<TUser> _resultSetToList(ResultSet rs) throws Exception{
		List<TUser> result = new ArrayList<TUser>();
		try {
			while (rs.next()) {
				TUser tUser = new TUser();
				tUser.setId(rs.getInt("id"));
				tUser.setAccount(rs.getString("account"));
				tUser.setName(rs.getString("name"));
				tUser.setPhotoPath(rs.getString("photo_path"));
				tUser.setDescription(rs.getString("description"));
				result.add(tUser);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new Exception();
		}
		return result;
	}

}